﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Vbyte.TextReader.Util;
using System.Web.Script.Serialization;

namespace Vbyte.TextReader
{
    /// <summary>
    /// 接口日志阅读器
    /// </summary>
    public class APILogReader : LogReader<APILog>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="APILogReader"/> class.
        /// </summary>
        /// <param name="logDir">日志存放目录</param>
        /// <param name="whichDay">日志阅读的日期</param>
        public APILogReader(string logDir, DateTime whichDay)
            : base(logDir, new string[] { "^API-(?<Date>\\d{4}\\-\\d{2}\\-\\d{2})" }, whichDay)
        {

        }

        private APILog _current = null;

        /// <summary>
        /// 前进阅读
        /// </summary>
        /// <returns>如果返回为true，则还有数据需要阅读。</returns>
        public override bool Read()
        {
            //Console.WriteLine("read.");
            bool result = CanRead();
            if (!result)
            {
                _current = null;
            }
            else
            {
            //读取实例数据开始
            ReadInstanceLog:

                string lineStr = Reader.ReadLine();
                if (lineStr == null)
                {
                    _current = null;
                    result = false;
                }
                else
                {
                    _current = new APILog();

                    string[] tArr = StringHelper.GetPatternMatchValue(lineStr, "@\\s(\\d{4}\\-\\d{2}\\-\\d{2}\\s\\d{2}:\\d{2}\\:\\d{2},\\d{3})\\s", 1);
                    if (tArr != null)
                    {
                        _current.LogTime = DateTime.ParseExact(tArr[0], "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.DateTimeFormatInfo.InvariantInfo);
                    }

                    //StringBuilder logBuilder = new StringBuilder(lineStr);
                    //logBuilder.AppendLine();

                    #region 逐行设置实例属性
                    while ((lineStr = Reader.ReadLine()) != null)
                    {
                        if (lineStr.Contains("-TimeFlag @"))
                        {
                            Reader.GotoLastLine();
                            break;
                        }
                        else
                        {
                            if (lineStr.StartsWith("完成加载数据："))
                            {
                                _current.RemoteURL = lineStr.Substring("完成加载数据：".Length);
                            }
                            else if (lineStr.StartsWith("参数："))
                            {
                                _current.Parameter = lineStr.Substring("参数：".Length);
                            }
                            else if (lineStr.StartsWith("下载数据"))
                            {
                                //下载数据所花时间：8909ms
                                _current.TotalSeconds = Convert.ToInt32(lineStr.Substring(lineStr.IndexOf("：") + 1).TrimEnd('m', 's'));
                            }
                            else if (lineStr.StartsWith("{"))
                            {
                                _current.JsonResult = lineStr;
                            }
                            else if (lineStr.Contains("]超时："))
                            {
                                //加载数据[3秒]超时：http://116.2
                                _current.IsTimeout = true;
                                _current.RemoteURL = lineStr.Substring(lineStr.IndexOf("：") + 1);

                                string[] tOutStr = StringHelper.GetPatternMatchValue(lineStr, "\\[(\\d+)秒\\]", 1);
                                _current.TotalSeconds = Convert.ToInt32(tOutStr[0]) * 1000;
                            }
                        }

                        //logBuilder.Append(lineStr);
                        //logBuilder.AppendLine();
                    }
                    #endregion

                    #region 检查内容判断是否正确，否则修改编码为UTF-8重读
                    if (string.IsNullOrEmpty(_current.RemoteURL))
                    {
                        Reader.ContentEncoding = Encoding.UTF8;
                        Reader.GotoLastMatchLine(m => m.Contains("-TimeFlag @"));
                        goto ReadInstanceLog;
                    }
                    #endregion

                    _current.LogCursor = String.Format("{0}-{1}", base.CurrentFileIndex, base.Reader.GetPosition());
                }
            }
            return result;
        }

        /// <summary>
        /// 阅读器当前实例
        /// </summary>
        /// <returns>返回阅读器当前所在的实例</returns>
        public override APILog GetCurrent()
        {
            return _current;
        }

    }


    /// <summary>
    /// 接口日志
    /// </summary>
    [Serializable]
    public class APILog : ILogItemTime
    {
        /// <summary>
        /// 下载数据所花时间
        /// </summary>
        public int TotalSeconds { get; set; }

        /// <summary>
        /// 接口远程地址
        /// </summary>
        public string RemoteURL { get; set; }


        /// <summary>
        /// 接口传递的参数
        /// </summary>
        public string Parameter { get; set; }

        /// <summary>
        /// 请求是否超时
        /// </summary>
        public bool IsTimeout { get; set; }

        /// <summary>
        /// 原始JSON结果
        /// </summary>
        [ScriptIgnore]
        public string JsonResult { get; set; }


        #region ILogItemTime 成员
        /// <summary>
        /// 日志时间
        /// </summary>
        /// <value></value>
        public DateTime LogTime
        {
            get;
            set;
        }

        /// <summary>
        /// 日志游标位置
        /// </summary>
        /// <value></value>
        public string LogCursor
        {
            get;
            set;
        }
        #endregion
    }

}
